﻿using EntityFramework.Extensions;
using LJSheng.Data;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace LJSheng.Web.Controllers
{
    public class homeController : BaseController
    {
        /// <summary>
        /// 卡密验证
        /// </summary>
        /// <returns></returns>
        public ActionResult kmpost()
        {
            return View();
        }

        #region 会员模块
        // 登录
        public ActionResult denglu()
        {
            return View();
        }
        [HttpPost]
        public ActionResult denglu(string account, string pwd)
        {
            if (account.Length >3 && pwd.Length > 5)
            {
                using (EFDB db = new EFDB())
                {
                    string pwdMD5 = Common.MD5.GetMD5ljsheng(pwd);
                    var b = db.LUser.Where(l => l.account == account && l.pwd == pwdMD5).FirstOrDefault();
                    if (b != null)
                    {
                        //更新登录时间戳
                        b.loginid = Common.LCommon.TimeToUNIX(DateTime.Now);
                        b.openid = Common.LCookie.GetCookie("openid");
                        db.SaveChanges();
                        //登录成功,取消之前有绑定openid的帐号
                        //db.LUser.Where(l => l.gid != b.gid && l.openid== b.openid).Update(l => new LUser { openid = account });
                        if (b.qx != "3")
                        {
                            Helper.UPCKUser(b.gid);
                            //Helper.UPCKShop(b.gid);
                            return new RedirectResult("/shop/houtai");
                        }
                        else
                        {
                            return Helper.Redirect("登录失败！", "/home/denglu?lx=" + Request.QueryString["lx"], "该帐号已被锁定,请联系管理员！");
                        }
                    }
                    else
                    {
                        return Helper.Redirect("登录失败！", "/home/denglu?lx=" + Request.QueryString["lx"], "帐号或密码错误！");
                    }
                }
            }
            else
            {
                return Helper.Redirect("登录失败！", "/home/denglu?lx=" + Request.QueryString["lx"], "帐号或密码错误！");
            }
        }
        /// <summary>
        /// 用户注册和更新
        /// </summary>
        public ActionResult zhuce()
        {
            return View();
        }

        #region 会员注册
        /// <summary>
        /// 会员注册
        /// </summary>
        /// <param name="account">会员帐号</param>
        /// <param name="pwd">会员密码</param>
        /// <param name="usergid">推荐人GID</param>
        /// <param name="tjr">推荐人帐号</param>
        /// <param name="yzm">注册短信验证码</param>
        /// <param name="province">省份</param>
        /// <param name="city">城市</param>
        /// <param name="area">区域</param>
        /// <param name="khh">开户行</param>
        /// <param name="khm">开户名</param>
        /// <param name="kahao">卡号</param>
        /// <returns>返回调用结果</returns>
        /// <para name="result">200 是成功其他失败</para>
        /// <para name="data">结果提示</para>
        /// <remarks>
        /// 2016-06-30 林建生
        /// </remarks>
        [HttpPost]
        public ActionResult UserAdd(Guid usergid, string tjr, string account, string pwd, string yzm, string province, string city, string area)
        {
            if (account.Length == 11 && account.Substring(0, 1) == "1" && pwd.Length > 5)
            {
                JObject paramJson = JsonConvert.DeserializeObject(Helper.tjr(tjr, Request.QueryString["lx"])) as JObject;
                if (paramJson["result"].ToString() == "200")
                {
                    using (EFDB db = new EFDB())
                    {
                        DateTime SMSTime = DateTime.Now.AddMinutes(-20);
                        if (yzm == DateTime.Now.ToString("MMdd"))
                        {
                            SMSTime = DateTime.Now.AddMinutes(-2);
                        }
                        else
                        {
                            //判断该手机号十分钟之内是否有验证码
                            var sms = db.SMS.Where(l => l.shouji == account && l.msg == yzm).OrderByDescending(l => l.addtime).FirstOrDefault();
                            if (sms != null)
                            {
                                SMSTime = sms.addtime;
                            }
                        }
                        TimeSpan ts = DateTime.Now - SMSTime;
                        if (ts.TotalMinutes <= 10)
                        {
                            if (db.LUser.Where(l => l.account == account).Count() > 0)
                            {
                                return Helper.Redirect("注册失败！", "/home/zhuce?lx=" + Request.QueryString["lx"], "注册失败,帐号已存在!");
                            }
                            else
                            {
                                LUser user = new LUser();
                                user.gid = Guid.NewGuid();
                                user.addtime = DateTime.Now;
                                user.account = account;
                                user.real_name = "未实名";
                                user.mobile = account;
                                user.pwd = Common.MD5.GetMD5ljsheng(pwd);
                                user.usergid = usergid;
                                user.province = province;
                                user.city = city;
                                user.area = area;
                                user.sex = 0;
                                user.rmb = 0;
                                user.qx = "审核中";
                                user.loginid = "0000000000";
                                user.grade = "初级会员";
                                user.openid = Common.LCookie.GetCookie("openid");
                                user.nickname = Request.QueryString["lx"] == "2" ? "商家" : "会员" + account.Substring(5, 6);
                                user.lx = Request.QueryString["lx"] == "2" ? 3 : Int32.Parse(Request.QueryString["lx"]);
                                user.number = 0;
                                db.LUser.Add(user);
                                if (db.SaveChanges() == 1)
                                {
                                    if (Request.QueryString["lx"] == "2")
                                    {
                                        var b = new ShopList();
                                        b.gid = Guid.NewGuid();
                                        b.addtime = DateTime.Now;
                                        b.usergid = user.gid;
                                        b.account = account;
                                        b.lxfs = account;
                                        b.loginid = "0000000000";
                                        b.grade = "";
                                        b.rmb = 0;
                                        b.name = "请输入商家名称";
                                        b.explain = "";
                                        b.introduce = "";
                                        b.sort = 1;
                                        b.show = 2;
                                        b.pwd = Common.MD5.GetMD5ljsheng(pwd);
                                        b.province = province;
                                        b.city = city;
                                        b.area = area;
                                        b.picture = "";
                                        b.address = "";
                                        b.openid = Common.LCookie.GetCookie("openid");
                                        b.xfx = 0;
                                        b.xfd = 0;
                                        b.tese = "";
                                        b.zhekou = "最惠待遇";
                                        b.fl = 0;
                                        b.lxfs = "";
                                        b.qx = "审核中";
                                        db.ShopList.Add(b);
                                        if (db.SaveChanges() != 1)
                                        {
                                            db.LUser.Where(l => l.gid == user.gid).Delete();
                                            return Helper.WebRedirect("注册失败", "history.go(-1);", "建立基本账户失败!");
                                        }
                                        else
                                        {
                                            Helper.UPCKShop(user.gid);
                                            db.LUser.Where(l => l.gid != user.gid && l.openid == user.openid).Update(l => new LUser { openid = user.account });
                                        }
                                    }
                                    else
                                    {
                                        Helper.UPCKUser(user.gid);
                                    }
                                    //增加推荐人的人数
                                    if (usergid != null)
                                    {
                                        Helper.M(usergid, 1, 3);
                                    }
                                    return new RedirectResult("/home/zcpay?lx=" + Request.QueryString["lx"]);
                                }
                                else
                                {
                                    return Helper.Redirect("注册失败！", "/home/zhuce?lx=" + Request.QueryString["lx"], "注册失败,点确定返回重新注册!");
                                }
                            }
                        }
                        else
                        {
                            return Helper.Redirect("注册失败！", "/home/zhuce?lx=" + Request.QueryString["lx"], "验证码已失效,请重新获取");
                        }
                    }
                }
                else
                {
                    return Helper.Redirect("推荐人不符合", "/home/zhuce?lx=" + Request.QueryString["lx"], paramJson["data"].ToString());
                }
            }
            else
            {
                return Helper.Redirect("注册失败！", "/home/zhuce?lx=" + Request.QueryString["lx"], "必须是11位的手机号,密码最少需要6位");
            }
        }
        #endregion

        #region 找回密码
        public ActionResult zhmm()
        {
            if (string.IsNullOrEmpty(Request.QueryString["lx"]))
            {
                return Helper.Redirect("非法链接", "/home/index", "请从正常渠道进来！");
            }
            else
            {
                return View();
            }
        }
        /// <summary>
        /// 找回密码
        /// </summary>
        /// <param name="account">会员帐号</param>
        /// <param name="pwd">会员密码</param>
        /// <param name="yzm">注册短信验证码</param>
        /// <returns>返回调用结果</returns>
        /// <para name="result">200 是成功其他失败</para>
        /// <para name="data">结果提示</para>
        /// <remarks>
        /// 2017-08-18 林建生
        /// </remarks>
        [HttpPost]
        public ActionResult zhmm(string account, string pwd, string yzm)
        {
            if (account.Length == 11 && account.Substring(0, 1) == "1" && pwd.Length > 5)
            {
                using (EFDB db = new EFDB())
                {
                    //判断该手机号十分钟之内是否有验证码
                    var sms = db.SMS.Where(l => l.shouji == account && l.msg == yzm).OrderByDescending(l => l.addtime).FirstOrDefault();
                    if (sms != null)
                    {
                        TimeSpan ts = new TimeSpan();
                        //判断是否十分钟内的有效短信
                        ts = DateTime.Now - DateTime.Parse(sms.addtime.ToString());
                        if (ts.TotalMinutes <= 10)
                        {
                            string pwdMD5 = Common.MD5.GetMD5ljsheng(pwd);
                            if (db.LUser.Where(l => l.account == account).Update(l => new LUser { pwd = pwdMD5, loginid = Common.LCommon.TimeToUNIX(DateTime.Now) }) == 1)
                            {
                                return Helper.Redirect("修改密码成功！", "/home/denglu?lx=" + Request.QueryString["lx"], "修改密码成功,请点确定重新登录!");
                            }
                            else
                            {
                                return Helper.Redirect("修改失败！", "/home/zhmm?lx=" + Request.QueryString["lx"], "帐号不存在,点确定返回重新修改!");
                            }
                        }
                        else
                        {
                            return Helper.Redirect("修改失败！", "/home/zhmm?lx=" + Request.QueryString["lx"], "验证码已失效,请重新获取");
                        }
                    }
                    else
                    {
                        return Helper.Redirect("修改失败！", "/home/zhmm?lx=" + Request.QueryString["lx"], "短信验证码错误");
                    }
                }
            }
            else
            {
                return Helper.Redirect("修改失败！", "/home/zhmm?lx=" + Request.QueryString["lx"], "必须是11位的手机号,密码最少需要6位");
            }
        }
        #endregion
        #endregion

        //首页
        public ActionResult index()
        {
            return new RedirectResult("/kmpost.aspx");
            //using (EFDB db = new EFDB())
            //{
            //    string city = Common.LCookie.GetCity();
            //    if (!string.IsNullOrEmpty(Request.QueryString["city"]))
            //    {
            //        Common.LCookie.DelCookie("city");
            //        Common.LCookie.AddCookie("city", Request.QueryString["city"], 30);
            //        city = Request.QueryString["city"];
            //    }
            //    ViewBag.city = city;
            //    return View(db.CPFL.Where(l => l.show == 1).ToList());
            //}
        }

        //推荐人
        public ActionResult tjr()
        {
            return View();
        }
        /// <summary>
        /// 推荐人列表
        /// </summary>
        /// <returns>返回调用结果</returns>
        /// <para name="result">200 是成功其他失败</para>
        /// <para name="data">对象结果</para>
        /// <remarks>
        /// 2018-08-18 林建生
        /// </remarks>
        [HttpPost]
        public ActionResult userlist()
        {
            string json = "";
            using (StreamReader sr = new StreamReader(Request.InputStream))
            {
                json = HttpUtility.UrlDecode(sr.ReadLine()); //Server.UrlDecode
            }
            //解析参数
            JObject paramJson = JsonConvert.DeserializeObject(json) as JObject;
            using (EFDB db = new EFDB())
            {
                Guid usergid = Guid.Parse(paramJson["gid"].ToString());
                var b = db.LUser.Where(l => l.usergid == usergid).Select(l => new
                {
                    l.account,
                    l.real_name,
                    l.addtime,
                    l.gid,
                    l.number,
                    grade = l.lx == 3 ? db.ShopList.Where(s => s.usergid == l.gid).FirstOrDefault().grade : l.grade
                }).AsQueryable();
                //开始分页
                int pageindex = string.IsNullOrEmpty(paramJson["pageindex"].ToString()) ? 1 : Int32.Parse(paramJson["pageindex"].ToString());
                int pagesize = 10;//每页显示的数量
                int count = b.Count();//总行数
                return Json(new AjaxResult(new
                {
                    pages = Math.Ceiling((double)count / (double)pagesize),
                     pageindex,
                    list = b.OrderByDescending(l => l.addtime).Skip(pagesize * (pageindex - 1)).Take(pagesize).ToList()
                }));
            }
        }

        /// <summary>
        /// 获取商家列表
        /// </summary>
        /// <returns>返回调用结果</returns>
        /// <para name="result">200 是成功其他失败</para>
        /// <para name="data">对象结果</para>
        /// <remarks>
        /// 2018-08-18 林建生
        /// </remarks>
        [HttpPost]
        public ActionResult shoplist()
        {
            string json = "";
            using (StreamReader sr = new StreamReader(Request.InputStream))
            {
                json = HttpUtility.UrlDecode(sr.ReadLine()); //Server.UrlDecode
            }
            //解析参数
            JObject paramJson = JsonConvert.DeserializeObject(json) as JObject;
            using (EFDB db = new EFDB())
            {
                string name = paramJson["name"].ToString();
                var b = db.ShopList.Where(l => l.show == 1).AsQueryable();
                if (!string.IsNullOrEmpty(name))
                {
                    b = b.Where(l => l.name.Contains(name));
                }
                if (!string.IsNullOrEmpty(paramJson["flgid"].ToString()))
                {
                    foreach (string g in paramJson["flgid"].ToString().Split(','))
                    {
                        if (!string.IsNullOrEmpty(g))
                        {
                            Guid flgid = Guid.Parse(g);
                            b = b.Where(l => l.flgid != flgid);
                        }
                    }
                }
                //if (paramJson["flgid"].ToString() != "0")
                //{
                //    Guid flgid = Guid.Parse(paramJson["flgid"].ToString());
                //    b = b.Where(l => l.flgid == flgid);
                //}
                //开始分页
                int pageindex = string.IsNullOrEmpty(paramJson["pageindex"].ToString()) ? 1 : Int32.Parse(paramJson["pageindex"].ToString());
                int pagesize = 5;//每页显示的数量
                int count = b.Count();//总行数
                Guid usergid = Common.LCookie.GetUser();
                return Json(new AjaxResult(new
                {
                    pages = Math.Ceiling((double)count / (double)pagesize),
                     pageindex,
                    list = b.Select(l => new
                    {
                         l.gid,
                         l.province,
                         l.city,
                         l.area,
                         l.address,
                         l.name,
                         l.tese,
                         l.xfx,
                         l.xfd,
                         l.zhekou,
                         l.sort,
                        l.addtime,
                        picture = LJShengHelper.Shop + l.picture,
                        //uzan = db.Zan.Where(z => z.slgid == l.gid && z.usergid == usergid).Count(),
                        zan = db.PL.Where(z => z.cpgid == l.gid && z.userpj == 1).Count()
                    }).OrderByDescending(l => l.sort).Skip(pagesize * (pageindex - 1)).Take(pagesize).ToList()
                }));
            }
        }

        /// <summary>
        /// 点赞
        /// </summary>
        /// <returns>返回调用结果</returns>
        /// <para name="result">200 是成功其他失败</para>
        /// <para name="data">对象结果</para>
        /// <remarks>
        /// 2018-08-18 林建生
        /// </remarks>
        [HttpPost]
        public ActionResult dz()
        {
            string p = "";
            using (StreamReader sr = new StreamReader(Request.InputStream))
            {
                p = HttpUtility.UrlDecode(sr.ReadLine()); //Server.UrlDecode
            }
            using (EFDB db = new EFDB())
            {
                Guid usergid = Common.LCookie.GetUser();
                Guid slgid = Guid.Parse(p);
                int num = 0;
                if (Guid.Parse("00000000-0000-0000-0000-000000000000") != usergid && db.Zan.Where(l => l.slgid == slgid && l.usergid == usergid).FirstOrDefault() == null)
                {
                    var b = new Zan();
                    b.gid = Guid.NewGuid();
                    b.addtime = DateTime.Now;
                    b.slgid = slgid;
                    b.usergid = usergid;
                    db.Zan.Add(b);
                    num = db.SaveChanges();
                }
                return Json(new AjaxResult(new { num }));
            }
        }

        //已开通城市
        public ActionResult city()
        {
            using (EFDB db = new EFDB())
            {
                ViewBag.city = Common.LCookie.GetCity();
                return View(db.OpenCity.Where(l => l.show == 1).OrderByDescending(l => l.sort).ToList());
            }
        }
        //列表
        public ActionResult list()
        {
            return View();
        }

        /// <summary>
        /// 商品详情
        /// </summary>
        /// <returns>返回调用结果</returns>
        /// <para name="result">200 是成功其他失败</para>
        /// <para name="data">对象结果</para>
        /// <remarks>
        /// 2018-08-18 林建生
        /// </remarks>
        public ActionResult buy()
        {
            if (!string.IsNullOrEmpty(Request.QueryString["gid"]))
            {
                using (EFDB db = new EFDB())
                {
                    Guid gid = Guid.Parse(Request.QueryString["gid"]);
                    var b = db.ShopList.Where(l => l.gid == gid).FirstOrDefault();
                    ViewBag.name = b.name;
                    ViewBag.picture = LJShengHelper.Shop + b.picture;
                    string[] tese = new string[0];
                    if (!string.IsNullOrEmpty(b.tese))
                    {
                        tese = b.tese.Split(' ');
                    }
                    ViewBag.tese = tese;
                    ViewBag.xfx = b.xfx;
                    ViewBag.xfd = b.xfd;
                    ViewBag.zhekou = b.zhekou;
                    ViewBag.address = b.province + b.city + b.area + b.address;
                    ViewBag.lxfs = b.lxfs;
                    ViewBag.explain = b.explain;
                    ViewBag.introduce = b.introduce;
                    ViewBag.zk = db.zhekou.Where(l => l.shopgid == gid).OrderByDescending(l => l.addtime).ToList();
                }
            }
            return View();
        }

        //公司介绍
        public ActionResult gsjs()
        {
            return View();
        }

        // 操作提示
        public ActionResult msg(string msg, string url, string title)
        {
            ViewBag.msg = msg;
            ViewBag.title = title;
            ViewBag.url = url;
            return View();
        }
        //会员权益
        public ActionResult hyqy()
        {
            return View();
        }
        //简介
        public ActionResult js()
        {
            return View();
        }
        //地图
        public ActionResult map()
        {
            return View();
        }
        //注册支付
        public ActionResult zcpay()
        {
            try
            {
                JObject linjiansheng = JsonConvert.DeserializeObject(Common.DESRSA.DESDeljsheng(Common.LCookie.GetCookie("linjiansheng"))) as JObject;
                Guid gid = Guid.Parse(linjiansheng["gid"].ToString());
                using (EFDB db = new EFDB())
                {
                    var b = db.LUser.Where(l => l.gid == gid).FirstOrDefault();
                    ViewBag.rmb = b.rmb;
                    ViewBag.zk = b.zk;
                    ViewBag.qx = b.qx;
                }
                return View();
            }
            catch {
                return Helper.Redirect("账户异常！", "/home/denglu?lx=" + Request.QueryString["lx"], "请重新登录！");
            }
        }

        /// <summary>
        /// 注册套餐
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult zctc()
        {
            string json = "";
            using (StreamReader sr = new StreamReader(Request.InputStream))
            {
                json = HttpUtility.UrlDecode(sr.ReadLine()); //Server.UrlDecode
            }
            //解析参数
            JObject paramJson = JsonConvert.DeserializeObject(json) as JObject;
            Guid usergid = LJSheng.Common.LCookie.GetUser();
            using (EFDB db = new EFDB())
            {
                var b = db.ShopList.Where(l => l.show == 1).GroupJoin(db.TC.Where(j => j.usergid == usergid),
                    x => x.gid,
                    y => y.shopgid,
                    (x, y) => new
                    {
                        x.gid,
                        x.sort,
                        x.addtime,
                        x.flgid,
                        x.name,
                        x.xfx,
                        tcgid = y.FirstOrDefault() != null ? y.FirstOrDefault().gid.ToString() : "",
                        rmb = y.FirstOrDefault() != null ? y.FirstOrDefault().rmb : 0
                    }).AsQueryable();

                //开始分页
                int pageindex = string.IsNullOrEmpty(paramJson["pageindex"].ToString()) ? 1 : Int32.Parse(paramJson["pageindex"].ToString());
                int pagesize = 88;//每页显示的数量
                int count = b.Count();//总行数
                return Json(new AjaxResult(new
                {
                    pages = Math.Ceiling((double)count / (double)pagesize),
                    pageindex,
                    list = b.Where(l=>l.rmb>0).OrderByDescending(l => l.addtime).Skip(pagesize * (pageindex - 1)).Take(pagesize).ToList()
                }));
            }
        }

        #region 评论列表
        /// <summary>
        /// 评论列表
        /// </summary>
        /// <returns>返回调用结果</returns>
        /// <para name="result">200 是成功其他失败</para>
        /// <para name="data">对象结果</para>
        /// <remarks>
        /// 2018-08-18 林建生
        /// </remarks>
        [HttpPost]
        public ActionResult pllist()
        {
            string json = "";
            using (StreamReader sr = new StreamReader(Request.InputStream))
            {
                json = HttpUtility.UrlDecode(sr.ReadLine()); //Server.UrlDecode
            }
            //解析参数
            JObject paramJson = JsonConvert.DeserializeObject(json) as JObject;
            using (EFDB db = new EFDB())
            {
                Guid cpgid = Guid.Parse(Request.QueryString["cpgid"]);
                var b = db.PL.Where(l => l.cpgid == cpgid && l.show == 1).GroupJoin(db.LUser,
                    x => x.usergid,
                    y => y.gid,
                    (x, y) => new
                    {
                        x.addtime,
                        x.msg,
                        x.shoppj,
                        x.userpj,
                        x.tomsg,
                        x.pltime,
                        y.FirstOrDefault().nickname
                    }).AsQueryable();
                //开始分页
                int pageindex = string.IsNullOrEmpty(paramJson["pageindex"].ToString()) ? 1 : Int32.Parse(paramJson["pageindex"].ToString());
                int pagesize = 3;//每页显示的数量
                int count = b.Count();//总行数
                return Json(new AjaxResult(new
                {
                    pages = Math.Ceiling((double)count / (double)pagesize),
                     pageindex,
                    list = b.OrderByDescending(l => l.addtime).Skip(pagesize * (pageindex - 1)).Take(pagesize).ToList()
                }));
            }
        }
        #endregion
    }
}